/*
Java source file
Copyright: Umschalt.com 2012
*/
package com.david.documentation.domain.dao.tags;

import com.david.documentation.domain.dao.AbstractDAO;
import com.david.documentation.domain.entities.tags.Tag;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

@Repository(value = "tagDao")
public class TagDaoImpl extends AbstractDAO<Tag> implements TagDao {

	@PersistenceContext
    private EntityManager entityManager;

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public Class<Tag> getClazz() {
		return Tag.class;
	}

	@Transactional
	public boolean checkforDublicate(String name) {
		Query query = getEntityManager().createQuery("from " + getClazz().getSimpleName() + " e where e.name = :aName");
        query.setParameter("aName", name);
        return query.getResultList().size() > 0;
	}

	@Transactional
	public Tag findTagByName(String name) {
		javax.persistence.Query query = getEntityManager().createQuery("from " + getClazz().getSimpleName() + " e where e.name = :aName");
        query.setParameter("aName", name );
		return (Tag)query.getSingleResult();
	}

	@Transactional
	public Number getNumberOfDokus(Long tagId) {
		javax.persistence.Query query = getEntityManager().createNativeQuery("SELECT COUNT(*) FROM tag,DOKU_TAGS WHERE DOKU_TAGS.TAG_ID =tag.TAG_ID AND tag.TAG_ID = :aName");
        query.setParameter("aName", tagId );
		return (Number)query.getSingleResult();
	}

	@Transactional
	public List<Tag> findTagsByName(String name) {
		javax.persistence.Query query = getEntityManager().createQuery("from " + getClazz().getSimpleName() + " e where e.name like :aName");
        query.setParameter("aName","%" +  name + "%" );
		query.setMaxResults(3);
		return query.getResultList();
	}
}
